package com.rimi.controller;

import com.rimi.bean.Doctor;
import com.rimi.bean.User;
import com.rimi.commons.CommonResult;
import com.rimi.commons.ResultStatus;
import com.rimi.model.vo.PasswordVo;
import com.rimi.model.vo.UserVo;
import com.rimi.service.UserService;
import com.rimi.util.PwdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author liHaiYang
 * @version V1.0
 * @Description: (用一句话描述该文件做什么)
 * @date 2021/7/7 16:53
 */
@RestController
@CrossOrigin
@Api(description = "用户账号管理",tags = "用户账号管理")
public class UserController {
    @Autowired
    UserService userService;

    @Value("${imgurl}")
    private String url;

    @PostMapping("user/register")
    @ResponseBody
    @ApiOperation("用户注册")
    public CommonResult register(@RequestBody UserVo userVo){
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        User user = new User();
        if(userVo.getUserGender() == null){
            user.setUserGender("保密");
        }
        user.setUserId(user1.getUserId());
        user.setUserPassword(userVo.getUserPassword());
        user.setUserNickname(userVo.getUserNickname());
        //用户密码如果不存在，就将该用户添加到数据库
        return userService.registerUer(user);
    }

    @GetMapping("show")
    @ResponseBody
    @ApiOperation("展示用户")
    public CommonResult<List<User>> show(){
        List<User> users = userService.showUser();
        return CommonResult.onSuccess(users);
    }

    @GetMapping("user/showCurrentUser")
    @ResponseBody
    @ApiOperation("展示当前用户")
    public CommonResult<User> showCurrentUser(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        return CommonResult.onSuccess(user);
    }

    @DeleteMapping("user/delete")
    @ResponseBody
    @ApiOperation("注销用户")
    public CommonResult delete(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
       int row = userService.deleteUserByUserId(user.getUserId());
        return row == 1? CommonResult.onSuccess(null):CommonResult.onFailed(ResultStatus.DELETE_FAILED);
    }

    @PutMapping("update")
    @ResponseBody
    @ApiOperation("编辑用户信息")
    public CommonResult update(@RequestBody User user){
        return userService.updateUser(user);
    }

    @PutMapping("user/updatePassword")
    @ResponseBody
    @ApiOperation("用户更改密码")
    public CommonResult updateUserByUsrId(@RequestBody PasswordVo passwordVo){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.hasText(passwordVo.getNewPassword())){
            //给输入的新密码以及旧密码加密
            String encode = PwdUtil.encode(passwordVo.getNewPassword());
            String encode1 = PwdUtil.encode(passwordVo.getOldPassWord());
            if(encode1.equals(user.getUserPassword())){
                return  userService.updateUserPasswordByUserId(user.getUserId(),encode);
            }
        }
        return CommonResult.onFailed(ResultStatus.UPDATE_PASSWORD_FAILED);
    }

    @PostMapping("/user/img/upload")
    @ResponseBody
    @ApiOperation("更改头像")
    public CommonResult imgUpload(MultipartFile file) {

        //生成一个随机字符串,作为新的文件名
        String str = UUID.randomUUID().toString();
        //获取用户上传文件的文件名
        String filename = file.getOriginalFilename();
        //根据最后一个 . 做分割,获取到用户的文件类型
        String split = filename.substring(filename.lastIndexOf("."));

        //创建一个输出流
        FileOutputStream outputStream = null;
        try {
            //将文件保存到nginx
            outputStream = new FileOutputStream("C:/nginx-1.16.1/html/userimg/" + str + split);
            outputStream.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //生成的随机字符串+文件名后缀,作为保存在数据库里的新文件名
        String finalImg = str + split;
        /**
         * 域名+文件夹名+图片名
         * url: 最上面的成员变量,加上@value,获取到yml文件里的值
         * userimg/: nginx里的文件夹
         */
        String imgurl = url + "userimg/" + finalImg;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Integer userId = user.getUserId();
        int row = userService.upLoadImg(imgurl,userId);
        return row>0 ? CommonResult.onSuccess(ResultStatus.OK):CommonResult.onFailed(ResultStatus.UPDATE_FAILED);
    }
    @PostMapping("user/add/{doctorId}")
    @ResponseBody
    @ApiOperation("用户关注医生")
    public CommonResult add(@PathVariable Integer doctorId){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user == null){
            return CommonResult.onFailed(ResultStatus.PLEASE_LOGIN);
        }else {
           int row = userService.addDoctorByUserId(doctorId,user.getUserId());
           return row == 1? CommonResult.onSuccess(null):CommonResult.onFailed(ResultStatus.ADD_FAILED);
        }
    }

    @GetMapping("user/show")
    @ResponseBody
    @ApiOperation("展示用户医生收藏")
    public CommonResult<List<Doctor>> showDoctor(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user == null){
            return CommonResult.onFailed(ResultStatus.PLEASE_LOGIN);
        }else {
            List<Doctor> doctors = userService.showDoctorByUserId(user.getUserId());
            if (doctors != null){
                return CommonResult.onSuccess(doctors);
            }
            return CommonResult.onFailed(ResultStatus.SHOW_FAILED);
        }
    }

    @DeleteMapping("user/delete/{doctorId}")
    @ResponseBody
    @ApiOperation("取消收藏的医生")
    public CommonResult delete(@PathVariable Integer doctorId){
        return userService.deleteDoctorBydoctorId(doctorId);
    }








}
